package light.head.controller.oa;

import java.io.FileOutputStream;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.AnnouncementDAO;
import light.head.dao.sys.FileDAO;
import light.head.dao.sys.MessageDAO;
import light.head.dao.sys.MessageTemplateDAO;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.Announcement;
import light.head.model.FileInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = Url.C_ANN)
public class AnnouncementController extends SupporterController{
	private final static String ann_photo_path = "upload/annPhoto/";
	
	private AnnouncementDAO annDAO;
	private FileDAO fileDAO;
	private OrganDAO organDAO;
	private UserInfoDAO userDAO;
	private MessageDAO msgDAO;
	private MessageTemplateDAO mtDAO;

	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.ANN_INIT);
	}

	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.RT, Parm.OC, Parm.START, Parm.END, Parm.TITLE,Parm.CUNAME);
		Integer oc  = organDAO.getRoot(cu_organCode(request)).getCode();
		if (annDAO.findByMap1(organDAO.getSonCodeList(oc),cu_code(request),map, pb ) == RESULT.SUCCESS) {
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.ANN_LIST);
	}
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(null == cu_organCode(request)) {
			PageBean pb = createPageBean(request);
			request.setAttribute(Parm.PAGE_BEAN, pb);
			return new ModelAndView(Url.ANN_INIT);
		}
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Announcement ann = annDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.ANN, ann);
		}
		return new ModelAndView(Url.ANN_EDIT);
	}
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Announcement ann = annDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.ANN, ann);
		}
		return new ModelAndView(Url.ANN_DETAIL);
	}

	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save(Announcement ann, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (null == ann.getCode()) {
			if (ann.getTitle().equals("")) {
				print(response, Msg.NULL_TITLE);
				return;
			} if (ann.getContent().equals("")) {
				print(response, Msg.NOT_FIND);
				return;
			}
			ann.setDeleted(false);
			ann.setOc(cu_organCode(request));
			ann.setCu(cu_code(request));
			ann.setOc(cu_organCode(request));
			ann.setCt(new Date());
			ann.setStatus(Sys.B_ONE);
			result = annDAO.add(ann);
			//消息通知审核人
			Integer ac =userDAO.findCode("彭先辉");
			String content = mtDAO.applyTofirst(ann,cu_realName(request));
			msgDAO.sendToUsers("【" + cu_realName(request) + "】提交公告申请单待审核通知", content, cu_code(request), cu_organCode(request),ac);
		} else {
			Announcement a = annDAO.get(ann.getCode());
			if(a.getCu() == cu_code(request) && a.getStatus() == 1){
				result = annDAO.update(ann);
			}else{
				print(response,Msg.EXISTS);
			}
		} 
		if (RESULT.SUCCESS == result) {
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}
	
	@RequestMapping(value = Url.DELETE)
	public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Announcement ann = annDAO .get(Integer.parseInt(code));
		ann.setDeleted(true);
		if (annDAO.update(ann) == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}

	/**
	 *上传一张图片和一个文件
	 * 
	 */
	@Transactional
	@RequestMapping(Url.UPLOAD)
	public void upload(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile pohto = multipartRequest.getFile(Parm.UPLOAD);
		String name = pohto.getOriginalFilename();

		if (isNotNull(name)) {
			String ext = name.substring(name.lastIndexOf(Sys.DOT) + 1);
			if (!ext.toUpperCase().equals(Sys.JPG)
					&& !ext.toUpperCase().equals(Sys.GIF)
					&& !ext.toUpperCase().equals(Sys.JPEG)
					&& !ext.toUpperCase().equals(Sys.BMP)
					&& !ext.toUpperCase().equals(Sys.PNG)) {
				print(response, Msg.FILE_TYPE_ERROR);
				return;
			}
			name = name.substring(0, name.lastIndexOf(Sys.DOT));

			UUID u = UUID.randomUUID();
			String uuid = u.toString().replace("-", "");
			String path = ann_photo_path + uuid + Sys.DOT + ext;
			String savePath = ConfigParm.getProjectPath() + path;
			FileOutputStream fo;
			int size = 0;

			try {
				fo = new FileOutputStream(savePath);
				size = pohto.getBytes().length;
				fo.write(pohto.getBytes());
				fo.close();
			} catch (Exception e) {
				print(response, Msg.ERROR);
				e.printStackTrace();
				throw new RuntimeException();
			}
			FileInfo f = new FileInfo();
			f.setDeleted(false);
			f.setExt(ext);
			f.setName(name);
			f.setUuid(uuid);
			f.setCt(new Date());
			f.setModule(Parm.ANN_PHOTO);
			f.setCu(cu_code(request));
			f.setOc(cu_organCode(request));
			f.setSize(size);
			fileDAO.add(f);

			StringBuffer result = new StringBuffer();
			result.append("<script type=\"text/javascript\">");
			if (isNotNull(path)) {
				result.append("window.parent.CKEDITOR.tools.callFunction(" + request.getParameter("CKEditorFuncNum") + ", '" + path + "')");
				result.append("</script>");
				result.append(path);
			} else {
				result.append("alert(\"上传失败，文件类型需要jpg、gif或png\")");
				result.append("</script>");
			}
			response.setHeader("Content-Type", "text/html; charset=UTF-8");
			print(response, result.toString());

		} else {
			print(response, Msg.ERROR);
		}
	}


	@Autowired
	public void setFileDAO(FileDAO fileDAO) {
		this.fileDAO = fileDAO;
	}
	@Autowired
	public void setAnnDAO(AnnouncementDAO annDAO) {
		this.annDAO = annDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setMsgDAO(MessageDAO msgDAO) {
		this.msgDAO = msgDAO;
	}
	@Autowired
	public void setMtDAO(MessageTemplateDAO mtDAO) {
		this.mtDAO = mtDAO;
	}
	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}
	
}
